<?php
class Model_Tank extends Model_WotHub {
    
	const ACTIF = 1;
	const RESERVE = 0;
	
    private $_baseUri = 'http://api.worldoftanks.eu/2.0/encyclopedia/tankinfo/';
    //http://api.worldoftanks.eu/2.0/encyclopedia/tankinfo/info/?application_id=d0a293dc77667c9328783d489c8cef73&tank_id=4929
    
    public function getTankInfo($tank_id) {
    	$tankExiste = $this->tankExiste($tank_id);
    	if ($tankExiste === false) {
    		$url = $this->_baseUri.'info/?application_id='.$this->_appId.'&tank_id='.$tank_id;
	    	$dataTank = $this->api_get_content($url, 'tankinfo.json');
	    	$tank = json_decode($dataTank, true);
	    	if (isset($tank['data'][$tank_id]) === true) {	    	
	    		$this->ajouterTank($tank['data'][$tank_id]);
	    	}
    	}
    	
	    $tank = $this->_getTankInfoFromDB($tank_id);    	
    	return $tank;
    }
    
    public function tankExiste($tank_id) {
    	$sql = 'SELECT tank_id FROM tanks WHERE tank_id = :tankid';
    	$bind = array(':tankid' => $tank_id);
    	$existe = $this->executerSql($sql, $bind);
    	if (count($existe) === 1) {
    		return true;
    	}
    	return false;
    }
    
    public function ajouterTank($tankInfo) {
    	$bind = array(':tankid' => $tankInfo['tank_id'],
				      ':name' => htmlentities($tankInfo['localized_name'], ENT_XML1),
				      ':nation' => $tankInfo['nation'],
				      ':level' => $tankInfo['level'],
				      ':type' => $tankInfo['type'],
				      ':image' => $tankInfo['image'],
				      ':contour' => $tankInfo['contour_image'],
				      ':small' => $tankInfo['image_small'],
				      ':premium' => $tankInfo['price_gold']);
     	$sql = 'INSERT INTO tanks 
    			VALUES (:tankid, :name, :nation, :level, :type, :image, :contour, :small, :premium)';
     	$insert = $this->executerSql($sql, $bind);
    }
    
    private function _getTankInfoFromDB($tank_id) {
    	$sql = 'SELECT * 
                FROM tanks t
                JOIN tankstats s ON s.tank_id = t.tank_id
                AND s.account_id = :account_id
                WHERE t.tank_id = :tankid';
    	$bind = array(':tankid' => $tank_id, ':account_id' => $_SESSION['account_id']);
    	$tank = $this->executerSql($sql, $bind);
    	return $tank;
    }
    
    public function ajouterEquipage($crew, $tankid) {
    	foreach ($crew as $membre) {
    		$roleid = $membre['role'];
    		$roleAd = '';
    		foreach ($membre['additional_roles_i18n'] as $adRole) {
    			$roleAd .= $adRole['role'].',';
    		} 
    		$sql = 'INSERT INTO crew VALUES(:tankid, :roleid, :roleAd)';
    		$bind = array(':roleid' => $roleid, 
    					  ':tankid' => $tankid,
    					  ':roleAd' => substr($roleAd,0 ,-1));
    		$insert = $this->executerSql($sql, $bind);
    	}
    }
    
    public static function activerTank($account_id, $tank_id, $inGarage, $new= false) {
        global $application;
        $pdo = new smartbokModele($application['bdd']);
        if ($inGarage === null) {
            $inGarage = 0;
        }
        $bind = array(':accountid' => $account_id,
                ':tankid' => $tank_id,
                ':actif' => $inGarage
        );
    	if ($new === true) {
    		$sql = 'INSERT INTO garage VALUES(:accountid, :tankid, :actif)';
    	}
    	else {
    		$sql = 'UPDATE garage set actif = :actif WHERE account_id = :accountid AND tank_id = :tankid';
    	}
        $modif = $pdo->executerSql($sql, $bind);
        return $modif;
    }
    
    public function retirerTank($account_id, $tank_id) {
        $bind = array(':accountid' => $account_id,
                ':tankid' => $tank_id,
                ':actif' => 0
        );
        $sql = 'UPDATE garage set actif = :actif WHERE account_id = :accountid AND tank_id = :tankid';
        $modif = $this->executerSql($sql, $bind);
        return $modif;
    }
    
    public function getCrew($tankid) {
        $sql = "SELECT c.*, r.image FROM crew c JOIN role r ON r.role_id = c.role_id WHERE tank_id = :tankid ORDER BY c.ordre";
        $bind = array(':tankid' => $tankid);
        $crew = $this->executerSql($sql, $bind);
        $this->crew = $crew;
        return $crew;        
    }
    
    public function getRole() {
        $sql = "SELECT * FROM role";
        $listeroles = $this->executerSql($sql);
        foreach ($listeroles as $role) {
            $roles[$role['role_id']] = $role;
        }
        return $roles;
    }
    
    public function preparerSkills($crewSkills) {
        $skills = array();
        $sql = "SELECT * FROM skills ORDER BY role_id";
        $listeSkills = $this->executerSql($sql);
        print_r($crewSkills);
        foreach ($listeSkills as $skill) {
            $find = false;
            foreach ($crewSkills as $crew) {
                if ($crew['skill_id'] === $skill['skill_id']) {
                    $find = true;
                }
            }
            if ($find === false) {
                $skills[] = $skill;
            }
        }
        return $skills;
    }


    public function getSkills() {
        $sql = "SELECT * FROM skills ORDER BY role_id";
        $listeSkills = $this->executerSql($sql);
        return $listeSkills;
    }
    
   
    public function getCrewSkills($tankid, $account_id) {
        $sql = "SELECT c.*, s.image, s.name, e.role_id, e.ordre
                FROM competences c 
                JOIN skills s on s.skill_id = c.skill_id 
                JOIN crew e on e.ordre = c.crew_id AND e.tank_id = :tankid
                JOIN role r on r.role_id = e.role_id
                WHERE c.tank_id = :tankid AND account_id = :account_id
                ORDER BY c.index";
        $bind = array(':tankid' => $tankid,
                      ':account_id' => $account_id);
        $crew = $this->executerSql($sql, $bind);
        $this->skills = $crew;
        return $crew;
    }
    
    public function getScore($tankId, $accountId) {
        $score = 0;
        if (isset($this->skills) === false) {
            $this->getCrewSkills($tankId, $accountId);
            $this->getCrew($tankId);
        }
        if (count($this->skills) > 0) {
            foreach ($this->skills as $skill) {
                $score+= $skill['valeur'];
            }
            $this->score = round($score/count($this->crew),0);
        }
        else {
            $this->score = 0;
        }
        return $this->score;
    } 
    
    public function enregistrerSkills() {
        $sql = 'INSERT INTO competences (tank_id, account_id, crew_id, skill_id, valeur) VALUES(:tankid, :accountid, :crewid, :skillid, :value)';
        $bind = array(':tankid' => $_POST['tank_id'],
                      ':accountid' => $_POST['account_id']);
        $this->executerSql('DELETE FROM competences WHERE tank_id = :tankid AND account_id = :accountid', $bind);
        foreach ($_POST as $key => $valeur) {
            if(in_array($key, array('tank_id', 'account_id')) === false) {
                //commander1#16
                $bind = array(":tankid" => $_POST['tank_id'],
                        ":accountid" => $_POST['account_id'],
                        ":crewid" => substr($key, strpos($key, '#')-1, 1),
                        ":skillid" => substr($key, strpos($key, '#')+1),
                        ":value" => $valeur);
                if ($valeur != 0) {
                    $res = $this->executerSql($sql, $bind);
                }
            }
        }
    }
    
    public static function getAllDataTank() {
        global $application;
        $pdo = new smartbokModele($application['bdd']);
        $tanks = $pdo->executerSql('SELECT * FROM tanks');
        foreach ($tanks as $tank) {
            $dataTanks[$tank['tank_id']] = $tank;
        }
        return $dataTanks;
        
    }
}

	